package cn.iocoder.yudao.module.alipay.didi.client.impl;

import cn.iocoder.yudao.module.alipay.didi.client.BasicClient;
import cn.iocoder.yudao.module.alipay.didi.client.DunionClientFactory;
import cn.iocoder.yudao.module.alipay.didi.client.UnionClient;
import cn.iocoder.yudao.module.alipay.didi.models.DunionClientConfig;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

public class DunionClientFactoryImpl implements DunionClientFactory {

    private final DunionClientConfig dunionClientConfig;

    private final AtomicReference<UnionClient> unionClientRef = new AtomicReference<>();

    public DunionClientFactoryImpl(DunionClientConfig dunionClientConfig) {
        this.dunionClientConfig = dunionClientConfig;
    }

    @Override
    public UnionClient getUnionClient() {
        return newClient(unionClientRef, UnionClientImpl::new);
    }

    //统一创建单例Client
    private synchronized <T extends BasicClient> T newClient(AtomicReference<T> reference,
                                                             Function<DunionClientConfig, T> factory) {
        T client = reference.get();

        if (Objects.isNull(client)) {
            client = factory.apply(dunionClientConfig);
            reference.lazySet(client);
        }

        return client;
    }

}
